package edu.tjpu.share.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

public class BitapCompress {

	private final static  int maxLength = 170;
	
	public static String GetImageBitmap(String imagePath) {
		try {

			//获取源图片的大小

			//Bitmap bm;

			BitmapFactory.Options opts = new BitmapFactory.Options();

			//当opts不为null时，但decodeFile返回空，不为图片分配内存，只获取图片的大小，并保存在opts的outWidth和outHeight

			BitmapFactory.decodeFile(imagePath,opts);

			int srcWidth = opts.outWidth;

			int srcHeight = opts.outHeight;

			int destWidth = 0;

			int destHeight = 0;

			double ratio = 0.0;		//缩放的比例


			//按比例计算缩放后的图片大小，maxLength是长或宽允许的最大长度

			if(srcWidth >srcHeight) {

			ratio = srcWidth / maxLength;

			destWidth = maxLength;

			destHeight = (int) (srcHeight / ratio);

			}else {

				ratio = srcHeight / maxLength;

				destHeight = maxLength;

				destWidth = (int) (srcWidth / ratio); 

			}

			//对图片进行压缩，是在读取的过程中进行压缩，而不是把图片读进了内存再进行压缩

			BitmapFactory.Options newOpts = new BitmapFactory.Options();

			//缩放的比例，缩放是很难按准备的比例进行缩放的，目前我只发现只能通过inSampleSize来进行缩放，其值表明缩放的倍数，SDK中建议其值是2的指数值

			newOpts.inSampleSize = (int) ratio + 1;

			//inJustDecodeBounds设为false表示把图片读进内存中

			newOpts.inJustDecodeBounds = false;

			//设置大小，这个一般是不准确的，是以inSampleSize的为准，但是如果不设置却不能缩放

			newOpts.outHeight = destHeight;

			newOpts.outWidth = destWidth;

			//添加尺寸信息，

			//tvInfo.append("\nWidth:" + newOpts.outWidth + " Height:" + newOpts.outHeight);

			//获取缩放后图片

			Bitmap destBm = BitmapFactory.decodeFile(imagePath,newOpts);
			
			
			if(destBm == null) {

				//showAlert("CreateFile" 0 "Create Failed" "OK" false);
				return "";

			} else {

				//文件命名，通过GUID可避免命名的重复
		
				String fileName = java.util.UUID.randomUUID().toString() + ".jpg";

				//另外定义：

				//ConfigManager.photoDir = getFileStreamPath(photoDirName) 
		
				//String photoDirName = "photo";要注意是根目录
				File file = new File("/sdcard/share/pic");
				if(!file.exists())
					file.mkdirs();

				File destFile = new File(file,fileName);

				//创建文件输出流

				OutputStream os = new FileOutputStream(destFile);

				//存储

				destBm.compress(CompressFormat.JPEG,100,os);

				os.close();

				//显示图片

				//setImgView(fileName);
		
				//setDrawable(fileName);
		
				//setDrawableAbsolute(fileName);
				return destFile.getAbsolutePath();

			}


		} catch(Exception e) {

			//showAlert("CreateFile" 0 e.toString() "OK" false);
			e.printStackTrace();
		}
		return "";

	}

}
